package moudle;


import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.os.StatFs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by eyesee on 2017/4/21.
 */

public class FileManagerMoudle {

    public List<String> getData(){

        List<String> list =  new ArrayList<>();

        for (int i = 0; i < 55; i++) {
            list.add(i+"文件夹");
        }
        return list;
    }

    /**获取sd卡路径*/
    public File getPath(){
        File sdDir = null;
        //判断sd卡是否存在
        boolean sdDirExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdDirExist){
            //获取根目录
            sdDir = Environment.getExternalStorageDirectory();
        }
        return sdDir;
    }

    /**获取路径*/
    public static String getDir(){
        String dir = new String();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                if (line.contains("secure")) continue;
                if (line.contains("asec")) continue;

                if (line.contains("fat")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        dir = dir.concat(columns[1] + "\n");
                    }
                } else if (line.contains("fuse")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        dir = dir.concat(columns[1] + "\n");
                    }
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dir;
    }


    /**扫描内存中视频文件并将符合要求的视频文件存入存入集合,此处只获取视频文件或*/
    public List<File> FileScan(File file){
        List<File> folderList = new ArrayList<>();      //folder类型集合
        List<File> videoList = new ArrayList<>();       //video类型集合
        List<File> fileList = new ArrayList<>();        //分类整理后的list集合

        File[] files = file.listFiles();
        if (files!=null){
            for (File item : files) {
                if (item.isDirectory()){
                    folderList.add(item);
                }else if (item.getName().endsWith(".mp4")){
                    videoList.add(item);
                }
            }
        }
        //FileList分类
        if (folderList!=null){
            for (int i = 0; i < folderList.size(); i++) {
                fileList.add(folderList.get(i));
            }
        }

        //Videolist分类
        if (videoList!=null){
            for (int j = 0; j < videoList.size(); j++) {
                fileList.add(videoList.get(j));
            }
        }
        return fileList;
    }


    /**计算sdcard剩余容量和总容量*/
    public List<String> getsize(){
        //存储剩余容量和总容量信息的集合,下标0为总容量,下标1为已用容量
        List<String> sdSizeInfo = new ArrayList<>();

        //是否插入内存
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File path = getPath();
            //文件路径
            StatFs statFs = new StatFs(path.getPath());
            //block的size
            long blockSize = statFs.getBlockSizeLong();
            //block的数量
            long totalBlocks = statFs.getBlockCountLong();
            //已用block数量
            long availableBlock = statFs.getAvailableBlocksLong();
            String[] total = filesize(totalBlocks * blockSize);         //总容量大小
            String[] availale = filesize(availableBlock * blockSize);   //已使用容量
            String used = availale[0]+availale[1];
            String all = total[0]+total[1];
            sdSizeInfo.add(0,used);
            sdSizeInfo.add(1,all);
        }
        return sdSizeInfo;
    }
    //返回数组,下标1代表大小,2代表单位 kB/MB
    public String[] filesize(long size){
        String str="";
        if (size>=1024){
            str = "KB";
            size /= 1024;

            if (size >=1024){
                str = "MB";
                size /= 1024;
            }
        }

        DecimalFormat formatter = new DecimalFormat();
        formatter.setGroupingSize(3);
        String[] result = new String[2];
        result[0] = formatter.format(size);
        result[1] = str;
        return result;
    }


    /**获取视频缩略图*/
    public Bitmap getVideoBitmap(File file){
        Bitmap bitmap =null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(file.getPath());
        bitmap = retriever.getFrameAtTime();

        retriever.release();
        return bitmap;
    }


    /**时间排序*/
    public List<File> getTimeSort(File file){
        List<File> fileList = new ArrayList<File>();
        if (file.exists() && file.isDirectory()){
            File[] files = file.listFiles();
            if (files!=null){
                for (File fil : files) {
                    fileList.add(fil);
                }
            }
            Collections.sort(fileList,new TimeComparator());
        }
        return fileList;            //排序后的File集合
    }
    //此处泛型为存储扫描文件信息的javabean
    private class TimeComparator implements Comparator<File>{

        @Override
        public int compare(File file1, File file2) {
            if ( file1.lastModified()< file2.lastModified()){
                return -1;
            }else {
                return 1;
            }
        }

        public FileFilter mFileFilter = new FileFilter() {
            @Override
            public boolean accept(File file) {
                String tmp = file.getName().toLowerCase();
                if (tmp.endsWith(".mov")||tmp.endsWith(".jpg")){
                    return true;
                }
                return false;
            }
        };
    }


    /**按名称排序*/
    public List<File> getNameSort(File filed){
        List<File> fileList = new ArrayList<File>();
        if (filed.exists() && filed.isDirectory()){
            File[] files = filed.listFiles();
            if (files!=null){
                for (int i = 0; i < files.length; i++) {
                    fileList.add(files[i]);
                }
            }
            Collections.sort(fileList,new NameComparator());
        }
        return fileList;        //排序后的File集合
    }
    //按名称降序排列
    private class NameComparator implements Comparator<File>{
        @Override
        public int compare(File file1, File file2) {
            return file2.getName().compareTo(file1.getName());
        }
    }
}
